package com.tau.egonetwork.gui.core; 
  
import org.eclipse.swt.SWT;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;

import com.tau.egonetwork.common.Log;
import com.tau.egonetwork.gui.Environment;
  
public abstract class BasicTab { 
    
	public static final String KEY_TAB = "tab";
	
    protected abstract void buildTab(Composite tabComposite);
    protected abstract String getTabText();
    protected abstract Image getTabImage();
    protected abstract boolean onTabClosed();
    
    private TabItem tabItem;
      
    public void createTab(final TabFolder parent) { 
    	
		Log.writeLineToLog("creatingTab for " + getTabText());

        tabItem = new TabItem(parent, SWT.NULL); 
        
        tabItem.setText(getTabText());
        tabItem.setImage(getTabImage());
        
        Composite itemComposite = new Composite(parent, SWT.NONE);
        GridLayout itemCompositeLayout = new GridLayout(1, true);
        itemCompositeLayout.verticalSpacing = 0;
        itemCompositeLayout.marginWidth = 0;
        itemCompositeLayout.marginHeight = 0;
        itemComposite.setLayout(itemCompositeLayout);
        itemComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
        
        Composite innerComposite = new Composite(itemComposite, SWT.BORDER);
        innerComposite.setLayout(new GridLayout(1, true));
        innerComposite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
                  
        Composite closeComposite = new Composite(itemComposite, SWT.NONE);
        closeComposite.setLayout(new GridLayout(1, true));
        closeComposite.setLayoutData(new GridData(SWT.FILL, SWT.RIGHT, true, false)); 
          
        Button closeButton = new Button(closeComposite, SWT.PUSH);
        closeButton.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, true, false));
        closeButton.setImage(Environment.ICON_CLOSE);
        closeButton.setText("Close"); 
        closeButton.addListener(SWT.Selection, new Listener() {
			
			@Override
			public void handleEvent(Event event) {
				if (onTabClosed()) {
					Log.writeLineToLog("closing " + getTabText() + " tab");
					tabItem.getControl().dispose();
					tabItem.dispose();
					if (parent.getItems().length == 0)
						parent.setVisible(false);
				}
			}
		});
        
        buildTab(innerComposite); 
        
        tabItem.setData(KEY_TAB, this);
        parent.setSelection(tabItem);
        tabItem.setControl(itemComposite);
        
        parent.setSelection(tabItem);
        
    } 
  
    public void setKey(String key) {
    	tabItem.setData(key, key);
    }

} 